package org.example.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectRequest;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.java.Log;
import org.example.bean.User;
import org.example.configs.OssConfig;
import org.example.dao.UserMapper;
import org.example.util.JwtUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.List;
import java.util.UUID;

import static org.example.controller.UserController.USER_STATUS_INACTIVE;

@Service
@AllArgsConstructor
@Log
public class UserServiceImpl implements UserService{
    private final JwtUtils jwtUtils;
    private final UserMapper userMapper;
    private final OssConfig ossConfig;
    private OSS ossClient;
    @Override
    @Transactional
    public User register(User user) {
        //第一步上传图片到Oss
        String originalFilename = user.getAvatarImgFile().getOriginalFilename();//文件名
        String fileExtension="";//文件扩展名
        if(originalFilename.contains(".")&&originalFilename!=null){
            fileExtension=originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        System.out.println("原文件名："+originalFilename+"\t扩展名"+fileExtension);
        String objectKey="files/"+ UUID.randomUUID().toString()+fileExtension; //保存的对象在oss中的地址
        PutObjectRequest putObjectRequest=null;
        try {
            putObjectRequest = new PutObjectRequest(ossConfig.getBucketName(), objectKey, user.getAvatarImgFile().getInputStream());
            ossClient.putObject(putObjectRequest);   //上传到Oss

            String fileUrl = ossConfig.getUrlPrefix() + File.separator + objectKey;
            user.setHead_url(fileUrl);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("上传文件到OSS失败"+ e.getMessage());
            throw new RuntimeException("上传文件到OSS失败"+e.getMessage());
        }


        userMapper.insert(user);
        return user;
    }

    @Override
    public User  login(User user) {
        // 根据用户名查询用户
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, user.getUsername());
        User user1 = userMapper.selectOne(queryWrapper);

        if (user1 == null || user1.getUser_status()==0) {
            throw new RuntimeException("用户不存在或已被禁用");
        }

        // 验证密码 (这里假设密码是加密存储的，你需要实现密码验证逻辑)
        if (!user1.getUserpwd().equals(user.getUserpwd())) {
            throw new RuntimeException("密码错误");
        }

        if (user1.getUser_status() == USER_STATUS_INACTIVE) {
            throw new RuntimeException("账号已被禁用");
        }

        //验证通过，返回用户
        user1.setToken(jwtUtils.generateToken(user1));// 生成Token并设置到用户对象
        return user1;// 返回用户对象
    }



    @Override
    @Transactional
    public User updateUser(Integer user_id,User user) {
        User oldUser = this.userMapper.selectById(user_id);
        if(oldUser==null){
            throw new RuntimeException("用户不存在"+user_id);
        }
        oldUser.setUsername(user.getUsername());
        oldUser.setGender(user.getGender());
        oldUser.setPhone(user.getPhone());
        oldUser.setEmail(user.getEmail());
        oldUser.setUser_status(user.getUser_status());
        if(user.getAvatarImgFile()!=null){
            //上传新图片
            String originalFilename = user.getAvatarImgFile().getOriginalFilename();//文件名
            String fileExtension="";//文件扩展名
            if(originalFilename.contains(".")&&originalFilename!=null){
                fileExtension=originalFilename.substring(originalFilename.lastIndexOf("."));
            }
            System.out.println("原文件名："+originalFilename+"\t扩展名"+fileExtension);
            String objectKey="files/"+ UUID.randomUUID().toString()+fileExtension; //保存的对象在oss中的地址
            try {
                PutObjectRequest putObjectRequest = new PutObjectRequest(ossConfig.getBucketName(), objectKey, user.getAvatarImgFile().getInputStream());
                ossClient.putObject(putObjectRequest);
                String fileUrl = ossConfig.getUrlPrefix() + File.separator + objectKey;
                oldUser.setHead_url(fileUrl);
            } catch (Exception e) {
                e.printStackTrace();
                log.info("上传文件到OSS失败"+ e.getMessage());
                throw new RuntimeException("上传文件到OSS失败"+e.getMessage());
            }
        }
        this.userMapper.updateById(oldUser);
        return oldUser;
    }

    @Override
    public User findByUsername(String username) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username);
        return userMapper.selectOne(queryWrapper);
    }

    @Override
    public List<User> findByStatus(Integer user_status) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUser_status, user_status);
        return userMapper.selectList(queryWrapper);
    }

    @Override
    @Transactional
    public User updateUserStatus(Integer user_id, Integer user_status) {
        User user = this.userMapper.selectById(user_id);
        if(user==null){
            throw new RuntimeException("用户不存在"+user_id);
        }
        user.setUser_status(user_status);
        this.userMapper.updateById(user);
        return user;
    }
}
